package com.rede.didiok.search.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.rede.didiok.common.dto.es.RankMemberEsModel;
import com.rede.didiok.common.utils.ListUtils;
import com.rede.didiok.common.utils.R;
import com.rede.didiok.search.config.ElasticsearchConfig;
import com.rede.didiok.search.constant.EsConstant;
import com.rede.didiok.search.feign.RankFeignService;
import com.rede.didiok.search.service.ESRankMemberService;
import com.rede.didiok.search.vo.*;

@Slf4j
@Service("eSRankMemberService")
public class ESRankMemberServiceImpl implements ESRankMemberService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private RankFeignService rankFeignService;

    //去es进行检索
    @Override
    public SearchResultVo search(SearchParamVo param) {
        //1、动态构建出查询需要的DSL语句
        SearchResultVo result = null;

        //1、准备检索请求
        SearchRequest searchRequest = buildSearchRequrest(param);

        try {
            //2、执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);

            //3、分析响应数据封装成我们需要的格式
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public Boolean bulkCreate(List<RankMemberEsModel> memberEsModels) throws IOException {

        //保存到es
        //1、给es中建立索引。didiok_rank，建立好映射关系。

        //2、给es中保存这些数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (RankMemberEsModel model : memberEsModels) {
            //1、构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.DIDIOK_RANK_MEMBER_INDEX);
            indexRequest.id(model.getMemberId().toString());
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        //TODO 1、如果批量错误
        boolean b = bulk.hasFailures();
        if(b) {
            log.error("商品上架错误");
        }
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("榜单成员发布完成：{}，返回数据：{}",collect,bulk.toString());


        return b;

    }

    /**
     * 批量更新文档
     *
     * @param memberEsModels
     * @return
     * @throws Exception
     */
    @Override
    public Boolean bulkUpdate(List<RankMemberEsModel> memberEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (RankMemberEsModel model : memberEsModels) {
            //1、构造保存请求
            UpdateRequest updateRequest = new UpdateRequest(EsConstant.DIDIOK_RANK_MEMBER_INDEX, model.getMemberId().toString());
            String s = JSON.toJSONString(model);
            updateRequest.doc(s, XContentType.JSON);

            bulkRequest.add(updateRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        //TODO 1、如果批量错误
        boolean b = bulk.hasFailures();
        if(b) {
            log.error("商品上架错误");
        }
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("榜单成员发布完成：{}，返回数据：{}",collect,bulk.toString());


        return b;
    }

    @Override
    public Boolean bulkDelete(List<String> docIds) throws IOException {

        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (String docId : docIds) {
            //1、构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.DIDIOK_RANK_MEMBER_INDEX);
            indexRequest.id(docId);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        //TODO 1、如果批量错误
        boolean b = bulk.hasFailures();
        if(b) {
            log.error("批量删除索引错误");
        }
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("批量删除索引完成：{}，返回数据：{}",collect,bulk.toString());


        return b;

    }

    /**
     * 准备检索请求
     * #模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequrest(SearchParamVo param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 1 查询、过滤（按照分类、榜单、投票区间、等级、属性）
         */
        // 1、构建 bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1、must-模糊匹配
        String keyword = param.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("memberName", keyword));
        }

        // 1.2、bool-filter
        // 1.2.1、按照三级分类id查询
        Long catalog3Id = param.getCatalog3Id();
        if (catalog3Id != null) {
            boolQuery.filter(QueryBuilders.termQuery("catId", catalog3Id));
        }

        // 1.2.2、按照榜单id查询
        List<Long> rankIds = param.getRankId();
        if (ListUtils.isNotEmpty(rankIds)) {
            boolQuery.filter(QueryBuilders.termsQuery("rankId", rankIds));
        }

        // 1.2.3、按照等级id查询
        List<Long> gradeIds = param.getGradeId();
        if (ListUtils.isNotEmpty(gradeIds)) {
            boolQuery.filter(QueryBuilders.termsQuery("gradeId", gradeIds));
        }

        // 1.2.4、按照所有指定的属性进行查询
        List<String> attrs = param.getAttrs();
        if (ListUtils.isNotEmpty(attrs)) {
            for (String attrStr : attrs) {
                // attrs=1_人工智能:嵌入式&attrs=2_陕西科技大学:中国计量大学
                // attr = 1_人工智能:嵌入式
                String[] s = attrStr.split("_");
                String attrId = s[0]; //检索的属性id
                String[] attrValues = s[1].split(":"); //这个属性的检索用的值

                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        // 1.2.5、按照投票数区间: 1_500/_500/500_
        String voteCount = param.getVoteCount();
        if (!StringUtils.isEmpty(voteCount)) {
            String[] s = voteCount.split("_");
            /*
             *         "range": {
             *             "voteCount": {
             *               "gte": 0,
             *               "lte": 6000
             *             }
             *           }
             */
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("voteCount");

            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {

                if (voteCount.startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (voteCount.endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        //把以前的所有条件都拿来进行封装
        sourceBuilder.query(boolQuery);

        /**
         * 2 排序，分页，高亮，
         */
        // 2.1、排序
        String sortStr = param.getSort();
        if (!StringUtils.isEmpty(sortStr)) {
            //sort=hotScore_asc/desc
            String[] s = sortStr.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        //2.2、分页
        /*
         * pageSize:5
         * pageNum:1  from:0  size:5  [0,1,2,3,4]
         * pageNum:2  from:5   size:5
         * from = (pageNum-1)*size
         */
        Integer pageNum = param.getPageNum();
        sourceBuilder.from((pageNum - 1) * EsConstant.PAGE_SIZE);
        sourceBuilder.size(EsConstant.PAGE_SIZE);

        //2.3、高亮
        if (!StringUtils.isEmpty(keyword)) {
            HighlightBuilder highlight = new HighlightBuilder();
            highlight.field("memberName");
            highlight.preTags("<b style='color:red'>");
            highlight.postTags("</b>");
            sourceBuilder.highlighter(highlight);
        }

        /**
         * 3 聚合分析
         */
        // 3.1、榜单聚合 rank_agg
        TermsAggregationBuilder rank_agg = AggregationBuilders.terms("rank_agg").field("rankId").size(50);
        // 3.1.1、榜单聚合的子聚合
        rank_agg.subAggregation(AggregationBuilders.terms("rank_name_agg").field("rankName").size(1));
        rank_agg.subAggregation(AggregationBuilders.terms("rank_logo_agg").field("rankLogo").size(1));
        // 聚合brand
        sourceBuilder.aggregation(rank_agg);

        // 3.2、等级聚合 grade_agg
        TermsAggregationBuilder grade_agg = AggregationBuilders.terms("grade_agg").field("gradeId").size(20);
        grade_agg.subAggregation(AggregationBuilders.terms("grade_name_agg").field("gradeName").size(1));
        // 聚合grade_agg
        sourceBuilder.aggregation(grade_agg);

        // 3.3、分类聚合 catalog_agg
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("cat_agg").field("catId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("cat_name_agg").field("catName").size(1));
        // 聚合catalog
        sourceBuilder.aggregation(catalog_agg);

        // 3.4、属性聚合 attr_agg
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(20);
        //聚合分析出当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前attr_id对应的所有可能的属性值attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        // 聚合attr
        sourceBuilder.aggregation(attr_agg);

        System.out.println("构建的DSL" + sourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.DIDIOK_RANK_MEMBER_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 构建结果数据
     *
     * @param response
     * @return
     */
    private SearchResultVo buildSearchResult(SearchResponse response, SearchParamVo param) {
        SearchResultVo searchResultVo = new SearchResultVo();
        /**
         * 从查询结果的source中获取
         */
        //1、返回的所有查询到的榜单成员
        SearchHits searchHits = response.getHits();
        List<RankMemberEsModel> esModels = new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        if (hits == null || hits.length <= 0) {
            return searchResultVo;
        }
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            RankMemberEsModel esModel = JSON.parseObject(sourceAsString, RankMemberEsModel.class);
            // 将高亮显示部分存储到esModel中
            if (!StringUtils.isEmpty(param.getKeyword())) {
                HighlightField memberName = hit.getHighlightFields().get("memberName");
                String string = memberName.getFragments()[0].string();
                esModel.setMemberName(string);
            }
            esModels.add(esModel);
        }
        searchResultVo.setRankMembers(esModels);

        /**
         * 从聚合信息中获取
         */
        //2、当前所有榜单成员信息涉及到的所有属性信息
        List<SearchResultVo.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        if (attr_agg != null) {
            ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
            if (attr_id_agg != null) {
                List<? extends Terms.Bucket> buckets = attr_id_agg.getBuckets();
                if (ListUtils.isNotEmpty(buckets)) {
                    for (Terms.Bucket bucket : buckets) {
                        //1、得到属性的id
                        long attrId = bucket.getKeyAsNumber().longValue();
                        //2、得到属性的名字
                        List<? extends Terms.Bucket> attrNameBuckets = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets();
                        String attrName = null;
                        if (ListUtils.isNotEmpty(attrNameBuckets)) {
                            attrName = attrNameBuckets.get(0).getKeyAsString();
                        }
                        //3、得到属性的所有值
                        List<? extends Terms.Bucket> attrValueBuckets = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets();
                        List<String> attrValues = new ArrayList<>();
                        if (ListUtils.isNotEmpty(attrValueBuckets)) {
                            attrValues = attrValueBuckets.stream().map(item -> {
                                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                                return keyAsString;
                            }).collect(Collectors.toList());
                        }
                        SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
                        attrVo.setAttrId(attrId);
                        attrVo.setAttrName(attrName);
                        attrVo.setAttrValue(attrValues);

                        attrVos.add(attrVo);
                    }
                }
            }
        }
        searchResultVo.setAttrs(attrVos);

        //3、当前所有榜单成员涉及到的所有榜单信息
        List<SearchResultVo.RankVo> rankVos = new ArrayList<>();
        ParsedLongTerms rank_agg = response.getAggregations().get("rank_agg");
        if (rank_agg != null) {
            List<? extends Terms.Bucket> rankBuckets = rank_agg.getBuckets();
            if (ListUtils.isNotEmpty(rankBuckets)) {
                for (Terms.Bucket bucket : rankBuckets) {
                    //1、得到榜单的id
                    long rankId = bucket.getKeyAsNumber().longValue();
                    //2、得到榜单的名
                    List<? extends Terms.Bucket> rankNameBuckets = ((ParsedStringTerms) bucket.getAggregations().get("rank_name_agg")).getBuckets();
                    String rankName = null;
                    if (ListUtils.isNotEmpty(rankNameBuckets)) {
                        rankName = rankNameBuckets.get(0).getKeyAsString();
                    }
                    //3、得到榜单的logo
                    List<? extends Terms.Bucket> rankLogoBuckets = ((ParsedStringTerms) bucket.getAggregations().get("rank_logo_agg")).getBuckets();
                    String rankLogo = null;
                    if (ListUtils.isNotEmpty(rankLogoBuckets)) {
                        rankLogo = rankLogoBuckets.get(0).getKeyAsString();
                    }

                    SearchResultVo.RankVo rankVo = new SearchResultVo.RankVo();
                    rankVo.setRankId(rankId);
                    rankVo.setRankName(rankName);
                    rankVo.setRankLogo(rankLogo);

                    rankVos.add(rankVo);
                }
            }
        }
        searchResultVo.setRanks(rankVos);

        //4、当前所有榜单成员涉及到的所有等级信息
        List<SearchResultVo.GradeVo> gradeVos = new ArrayList<>();
        ParsedLongTerms grade_agg = response.getAggregations().get("grade_agg");
        if (grade_agg != null) {
            List<? extends Terms.Bucket> gradeBuckets = grade_agg.getBuckets();
            if (ListUtils.isNotEmpty(gradeBuckets)) {
                for (Terms.Bucket bucket : gradeBuckets) {
                    //得到等级id
                    long gradeId = bucket.getKeyAsNumber().longValue();
                    //得到等级名
                    List<? extends Terms.Bucket> gradeNameBuckets = ((ParsedStringTerms) bucket.getAggregations().get("grade_name_agg")).getBuckets();
                    String gradeName = null;
                    if (ListUtils.isNotEmpty(gradeNameBuckets)) {
                        gradeName = gradeNameBuckets.get(0).getKeyAsString();
                    }
                    SearchResultVo.GradeVo gradeVo = new SearchResultVo.GradeVo();
                    gradeVo.setGradeId(gradeId);
                    gradeVo.setGradeName(gradeName);

                    gradeVos.add(gradeVo);
                }
            }
        }
        searchResultVo.setGrades(gradeVos);

        //5、当前所有榜单成员涉及到的所有分类信息
        List<SearchResultVo.CategoryVo> categoryVos = new ArrayList<>();
        ParsedLongTerms cat_agg = response.getAggregations().get("cat_agg");
        if (cat_agg != null) {
            List<? extends Terms.Bucket> catBuckets = cat_agg.getBuckets();
            if (ListUtils.isNotEmpty(catBuckets)) {
                for (Terms.Bucket bucket : catBuckets) {
                    //得到分类id
                    long catId = bucket.getKeyAsNumber().longValue();
                    //得到分类名
                    List<? extends Terms.Bucket> catNameBuckets = ((ParsedStringTerms) bucket.getAggregations().get("cat_name_agg")).getBuckets();
                    String catName = null;
                    if (ListUtils.isNotEmpty(catNameBuckets)) {
                        catName = catNameBuckets.get(0).getKeyAsString();
                    }
                    SearchResultVo.CategoryVo categoryVo = new SearchResultVo.CategoryVo();
                    categoryVo.setCatId(catId);
                    categoryVo.setCatName(catName);

                    categoryVos.add(categoryVo);
                }
            }
        }
        searchResultVo.setCategorys(categoryVos);

        /**
         * 分页信息封装
         */
        //6、分页信息:页码
        searchResultVo.setPageNum(param.getPageNum());
        //6、分页信息:总记录数
        long total = searchHits.getTotalHits().value;
        searchResultVo.setTotal(total);
        //6、分页信息:总页码-计算  11/2 = 5 .. 1
        int totalPages = (int) total % EsConstant.PAGE_SIZE == 0 ? (int) total / EsConstant.PAGE_SIZE : ((int) total / EsConstant.PAGE_SIZE + 1);
        searchResultVo.setTotalPages(totalPages);

        // 6、分页信息:显示每一页的页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResultVo.setPageNavs(pageNavs);

        /**
         * 面包屑导航功能
         */
        //7.1、构建属性的面包屑导航功能
        List<SearchResultVo.NavVo> allNavVos = new ArrayList<>();
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResultVo.NavVo> navVos = param.getAttrs().stream().map(attr -> {
                // 7.1.1、分析每个attrs传过来的查询参数值。
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                // attrs=1_人工智能:嵌入式
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = rankFeignService.attrInfo(Long.parseLong(s[0]));
                // 将查询参数 param.getAttrs() 中的attrId进行汇总
                searchResultVo.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                // 7.1.2、取消了这个面包屑以后，我们要跳转到一个新的url,需要将这个新的请求地址的url里面的当前参数置空
                // attrs=1_人工智能:嵌入式
                // 拿到所有的查询条件的字符串，并从中去掉当前属性和属性值。
                String replace = replaceQueryString(param, attr, "attrs");
                // setLink()是存储一个url，这个url是指：如果当前这个面包屑去除之后，应该跳转到的url地址
                navVo.setLink("http://search.didiok.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());


            allNavVos.addAll(navVos);
        }

        //7.2 榜单的面包屑导航功能
        if (ListUtils.isNotEmpty(param.getRankId())) {

            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();

            navVo.setNavName("榜单");
            // 远程查询所有榜单
            R r = rankFeignService.ranksInfo(param.getRankId());
            if (r.getCode() == 0) {
                List<RankResponseVo> ranks = r.getData("rank", new TypeReference<List<RankResponseVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (RankResponseVo rankResponseVo : ranks) {
                    buffer.append(rankResponseVo.getRankName() + ";");
                    replace = replaceQueryString(param, rankResponseVo.getRankId() + "", "rankId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.didiok.com/list.html?" + replace);
            }

            allNavVos.add(navVo);
        }

        //7.3 等级的面包屑导航功能
        if (ListUtils.isNotEmpty(param.getGradeId())) {

            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();

            navVo.setNavName("等级");
            // 远程查询所有等级
            R r = rankFeignService.gradesInfo(param.getGradeId());
            if (r.getCode() == 0) {
                List<GradeResponseVo> grades = r.getData("grade", new TypeReference<List<GradeResponseVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (GradeResponseVo gradeResponseVo : grades) {
                    buffer.append(gradeResponseVo.getGradeName() + ";");
                    replace = replaceQueryString(param, gradeResponseVo.getGradeId() + "", "gradeId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.didiok.com/list.html?" + replace);
            }

            allNavVos.add(navVo);
        }

        //7.4 分类的面包屑导航功能
        if (null != param.getCatalog3Id()) {

            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();

            navVo.setNavName("分类");
            // 远程查询所有分类
            R r = rankFeignService.categoryInfo(param.getCatalog3Id());

            if (r.getCode() == 0) {
                CategoryResponseVo category = r.getData("category", new TypeReference<CategoryResponseVo>() {
                });
                String replace = replaceQueryString(param, category.getCatId() + "", "catId");

                navVo.setNavValue(category.getCatName());
                navVo.setLink("http://search.didiok.com/list.html?" + replace);
            }

            allNavVos.add(navVo);
        }
        searchResultVo.setNavs(allNavVos);


        return searchResultVo;

    }

    /**
     * 1.对入参中的某个参数进行UTF-8转码，并将转码后的空格进行替换
     * 2.将请求参数地址移除掉该查询参数，得到一个新的请求地址
     * @param param
     * @param value
     * @param key
     * @return
     */
    private String replaceQueryString(SearchParamVo param, String value,String key) {
//        String encode = null;
//        //1.对入参中的某个参数进行UTF-8转码，并将转码后的空格进行替换
//        try {
//            encode = URLEncoder.encode(value, "UTF-8");
//            // 前端传递过来的空格被解码成+，替换成%20
//            encode = encode.replace("+","%20");//浏览器对空格编码和java不一样，差异化处理
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        // 2.将请求参数地址移除掉该查询参数,得到一个新的请求地址
        // TODO 先注释掉吧
//        String replacedStr = null;
//        if(param.get_queryString().indexOf("&") != -1 ) {
//            replacedStr = "&" + key + "=" + value;
//        }else {
//            replacedStr = key + "=" + value;
//        }
//        return param.get_queryString().replace(replacedStr, "");
        return param.get_queryString();
    }


}
